package com.java.demo.controller;

import com.java.demo.pojo.User;
import com.java.demo.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;

/**
 * 前端控制器
 *
 * @author flh
 * @since 2022-07-15
 */
@RestController
@RequestMapping("/user")
public class UserController {

  // 注入
  @Autowired IUserService userService;

  /**
   * 用户列表
   *
   * @return
   */
  @RequestMapping("/list")
  public HashMap<String, Object> List() {
    HashMap<String, Object> map = new HashMap<String, Object>();
    userService.list();
    List<User> users = userService.list();
    map.put("users", users);
    return map;
  }

  /**
   * 新增用户
   *
   * @param user
   * @return
   */
  @RequestMapping("/addUser")
  public HashMap<String, Object> addUser(User user) {
    HashMap<String, Object> map = new HashMap<>();
    if (StringUtils.isBlank(user.getUserName())) {
      map.put("info", "失败！用户名不允许为空！");
      return map;
    }
    if (StringUtils.isBlank(user.getSex())) {
      map.put("info", "失败！性别不允许为空！");
      return map;
    }
    if (StringUtils.isBlank(user.getAge())) {
      map.put("info", "失败！年龄不允许为空！");
      return map;
    }
    if (StringUtils.isBlank(user.getAddress())) {
      map.put("info", "失败！住址不允许为空！");
      return map;
    }
    if (userService.save(user) == true) {
      map.put("info", "成功");
      return map;
    }
    map.put("info", "写入失败！");
    return map;
  }
}
